package com.yunkeji.config.keymonitor.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunkeji.api.call.bo.StartCancelBo;
import com.yunkeji.api.call.mapper.ApiCallSheetInfoMapper;
import com.yunkeji.api.call.service.CallService;
import com.yunkeji.common.constant.CacheConstants;
import com.yunkeji.common.constant.SysIdConstant;
import com.yunkeji.common.enums.app.CallSheetStatus;
import com.yunkeji.config.keymonitor.config.RedisListenerFactory;
import com.yunkeji.config.keymonitor.config.RedisListenerStrategy;
import com.yunkeji.dao.domain.CallSheetInfo;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 老张
 * @version V1.0
 * @description 通话保持上报超时自动解散房间,规定在一定时间需要上报心跳,当两台机器都上报,了,这个key会重置,如果一台不上报,不会重置,监听到以后会直接解散房间
 * @date 2021/11/15 14:10
 * @update 2021/11/15 14:10
 */
@Component
@AllArgsConstructor
@Slf4j
public class CallHangUpUpdate implements InitializingBean, RedisListenerStrategy {

    private final ApiCallSheetInfoMapper apiCallSheetInfoMapper;
    private final CallService callService;

    @Override
    public void afterPropertiesSet() throws Exception {
        RedisListenerFactory.put(CacheConstants.CALL_BILL_UPDATE, this);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(String keyInfo) {
        log.info("检测到通话保持挂断,KEY[{}]", keyInfo);
        String ucid = keyInfo.replace(CacheConstants.CALL_BILL_UPDATE, "");
        // TODO 用户状态更新
        CallSheetInfo callSheetInfo =
                apiCallSheetInfoMapper.selectOne(
                        Wrappers.lambdaQuery(CallSheetInfo.class).eq(CallSheetInfo::getUcid, ucid));
        if (callSheetInfo == null) {
            log.error("话单不存在,{}", ucid);
            return;
        }
        StartCancelBo cancelBo = new StartCancelBo();
        cancelBo.setCancelType(CallSheetStatus.已接通系统挂断.getCode());
        cancelBo.setUcid(callSheetInfo.getUcid());
        cancelBo.setBillUid(SysIdConstant.系统);
        cancelBo.setRemark("检测到通话保持挂断");
        callService.startCancel(cancelBo);
    }
}
